/**
 * Created by Tuffy on 16/8/23.
 */
'use strict';

var xlsx = require('node-xlsx');
var formidable = require('formidable');
var fs = require('fs');
var _ = require('underscore');
var constant = require('../resource/base-config');
var baseConfig = require('../resource/base-config');
var adminHost = constant.adminHost;
var host = constant.tmsdriverHost;
var kashost=constant.kasHost;

var request = require('request');
var sessionUtils = require('../utils/session-utils');



/**
 * post request
 * @param url
 * @param req
 * @param callback
 */
function post1(url, req, callback) {
    var host = req.query.host;
    request.post({
        json: true,
        url: host + url,
        headers: {
            'Authorization': parseUseSession(req)
        },
        form: req.body
    }, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            var result = body;
            // 登录写入token
            if (result && result.success && result.Authorization) {
                sessionUtils.setToken(req, result.Authorization);
                delete result.Authorization;
            }
            callback(result);
        } else {
            // callback({success: false, message: '请求异常'});
            callback(null);
        }
    });
};


/**
 * post request
 * @param url
 * @param req
 * @param callback
 */
function post(url, req, callback) {
    request.post({
        url: host + url,
        headers: {
            'Authorization': parseUseSession(req)
        },
        form: req.body
    }, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            var result = JSON.parse(body);
            if (body.indexOf('{') >= 0 || body.indexOf('[') >= 0) {
                result = JSON.parse(body)
            } else {
                result = {
                    data: body,
                    message: null,
                    messageCode: null,
                    success: true
                };
            }
            // 登录写入token
            if (result && result.data && result.data.Authorization) {
                sessionUtils.setToken(req, result.data.Authorization);
                delete result.data.Authorization;
            }
            callback(result);
        }
        else {
            callback(null);
        }
    });
};


/**
 * post request
 * @param url
 * @param req
 * @param callback
 */
function postkas(url, req, callback) {
    request.post({
        url: kashost + url,
        form: req.body
    }, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            var result = JSON.parse(body);
            if (body.indexOf('{') >= 0 || body.indexOf('[') >= 0) {
                result = JSON.parse(body)
            } else {
                result = {
                    data: body,
                    message: null,
                    messageCode: null,
                    success: true
                };
            }
            // 登录写入token
            if (result && result.data && result.data.Authorization) {
                sessionUtils.setToken(req, result.data.Authorization);
                delete result.data.Authorization;
            }
            callback(result);
        }
        else {
            callback(null);
        }
    });
};


/**
 * post request
 * @param url
 * @param req
 * @param callback
 */
function postotd(url, req, callback) {
    request.post({
        url: kashost + url,
        form: req.body
    }, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            var result = JSON.parse(body);
            if (body.indexOf('{') >= 0 || body.indexOf('[') >= 0) {
                result = JSON.parse(body)
            } else {
                result = {
                    data: body,
                    message: null,
                    messageCode: null,
                    success: true
                };
            }
            // 登录写入token
            if (result && result.data && result.data.Authorization) {
                sessionUtils.setToken(req, result.data.Authorization);
                delete result.data.Authorization;
            }

            callback(result);
        }
        else {
            callback(null);
        }
    });
};

module.exports = uploadService;
function uploadService() {};


/**
 * 解析token使用
 * @param host 主机地址
 * @returns {string} token
 */
function parseUseSession(req) {
    var sessionToken = null;
    var host = req.query.host;
    if (host !== adminHost) {
        sessionToken = sessionUtils.getBaseToken(req);
    } else {
        sessionToken = sessionUtils.getToken(req);
    }
    return sessionToken;
};

/**
 * 传递数据到服务器
 * @param list 列表
 */
function uploadExcel2Service(list, callback) {
    var sheet = null;
    var keys = ['routeName', 'originProvinceName', 'originAreaName', 'destProvinceName', 'destAreaName', 'miles', 'effectiveDateString', 'currentValue'];
    var requestList = [];
    var isXls = false;
    if (list && list.length > 0) {
        isXls = true;
        sheet = list[0];
        if (sheet.data.length > 4) {
            for (var j = 4; j < sheet.data.length; j++) {
                var row = sheet.data[j];
                var cellObj = {};
                for (var i = 0; i < row.length; i++) {
                    if (i === 1 && !row[i]) {
                        break;
                    }
                    if (i < keys.length) {
                        cellObj[keys[i]] = row[i] || '';
                    }
                }
                if (cellObj.routeName) {
                    if (typeof cellObj.effectiveDateString != 'string') {
                        if (callback) callback(null, '提车日期格式不正确，应为yyyy-MM-dd');
                        return;
                    }
                    var date = new Date(cellObj.effectiveDateString.replace(/-/gi,"/"));
                    if (!date.getFullYear()) {
                        if (callback) callback(null, '提车日期格式不正确，应为yyyy-MM-dd');
                        return;
                    }
                    requestList.push(cellObj);
                }
            }
            _.map(requestList, function () {
                // item.isUrgent = item.isUrgent == baseConfig.available.enable ? true : false;
                // item.isSencondhand = item.isSencondhand == baseConfig.available.enable ? false : true;
                // item.isMobile = item.isMobile == baseConfig.available.enable ? true : false;
                // item.isPick = item.isPick == baseConfig.available.enable ? true : false;
                // item.isDeliv = item.isDeliv == baseConfig.available.enable ? true : false;
                // if (item.deliveryTime == baseConfig.deliveryTime.am) {
                //     item.deliveryTime = 0;
                // } else if (item.deliveryTime == baseConfig.deliveryTime.pm) {
                //     item.deliveryTime = 1;
                // }
            });
        }
    }
    if (!isXls) {
        if (callback) callback(null);
    } else {
        if (callback) callback(requestList);
    }
};

/**
 * 传递数据到服务器
 * @param list 列表
 */
function uploadExcel1Service(list, callback) {
    var sheet = null;
    var keys = ['vehicleClassName', 'vehicleClassId', 'tankVolume', 'oilTypeName', 'standardOc', 'effectiveDateString'];
    var requestList = [];
    var isXls = false;
    if (list && list.length > 0) {
        isXls = true;
        sheet = list[0];
        if (sheet.data.length > 4) {
            for (var j = 4; j < sheet.data.length; j++) {
                var row = sheet.data[j];
                var cellObj = {};
                for (var i = 0; i < row.length; i++) {
                    if (i === 1 && !row[i]) {
                        break;
                    }
                    if (i < keys.length) {
                        cellObj[keys[i]] = row[i] || '';
                    }
                }
                if (cellObj.vehicleClassName) {
                    if (typeof cellObj.effectiveDateString != 'string') {
                        if (callback) callback(null, '提车日期格式不正确，应为yyyy-MM-dd');
                        return;
                    }
                    var date = new Date(cellObj.effectiveDateString.replace(/-/gi,"/"));
                    if (!date.getFullYear()) {
                        if (callback) callback(null, '提车日期格式不正确，应为yyyy-MM-dd');
                        return;
                    }
                    requestList.push(cellObj);
                }
            }
            _.map(requestList, function () {
                // item.isUrgent = item.isUrgent == baseConfig.available.enable ? true : false;
                // item.isSencondhand = item.isSencondhand == baseConfig.available.enable ? false : true;
                // item.isMobile = item.isMobile == baseConfig.available.enable ? true : false;
                // item.isPick = item.isPick == baseConfig.available.enable ? true : false;
                // item.isDeliv = item.isDeliv == baseConfig.available.enable ? true : false;
                // if (item.deliveryTime == baseConfig.deliveryTime.am) {
                //     item.deliveryTime = 0;
                // } else if (item.deliveryTime == baseConfig.deliveryTime.pm) {
                //     item.deliveryTime = 1;
                // }
            });
        }
    }
    if (!isXls) {
        if (callback) callback(null);
    } else {
        if (callback) callback(requestList);
    }
};


/**
 * 传递数据到服务器(自有OTD)
 * @param list 列表
 */
function uploadOTDExcel2Service(list, callback) {
    var sheet = null;
    var keys = ['gmtOrderReceived', 'customerName','orderCode','dispatchCode','vehicleVin',
        'vehicleCode', 'vehicleSettleCode','s2pName','s2pAddrDetail', 's2pContactMobile',
        's2pAddrProvince', 's2pAddrCity','gmtDispatch', 'gmtOutboundCust', 'gmtInboundPickup',
        'gmtSap', 'gmtPod', 'pickupTeam', 'pickupNode', 'pickupExcepType',
        'pickupExcepComment', 'pickupExcepResponsible', 'pickupExcepStatus', 'gmtPhase1Dispatch', 'gmtPhase1Depart',
        'transMode','phase1Dest', 'phase1Carriager', 'phase1CarriagePlate', 'phase1Driver',
        'phase1DriverMobile','inBoundExcepType','inBoundExcepComment','inBoundExcepReponsible','inBoundExcepStatus',
        'location','gmtPhase1Arrival','phase1ExcepType', 'phase1ExcepRemark', 'phase1ExcepResponsible',
        'phase1ExcepStatus', 'phase2Dest', 'gmtPhase2Inbound', 'gmtPhase2Depart', 'phase2Carriager',
        'phase2CarriagePlate', 'phase2Driver', 'phase2DriverPhone', 'phase2ExcepType', 'phase2ExcepRemark',
        'phase2ExcepResponsible', 'phase2ExcepStatus', 'gmtPhase2Arrival', 'phase3Dest', 'gmtPhase3Inbound',
        'gmtPhase3Depart', 'phase3Carriager', 'phase3CarriagePlate', 'phase3Driver', 'phase3DriverPhone',
        'phase3ExcepType', 'phase3ExcepRemark', 'phase3ExcepResponsible', 'phase3ExcepStatus', 'gmtPhase3Arrival',
        'gmtStandardDelivery' , 'gmtActualDelivery', 'orderStatus', 'gmtArrival'
    ];

    var requestList = [];
    var isXls = false;
    if (list && list.length > 0) {
        isXls = true;
        sheet = list[0];
        if (sheet.data.length > 1) {
            for (var j = 1; j < sheet.data.length; j++) {
                var row = sheet.data[j];
                var cellObj = {};
                for (var i = 0; i < row.length; i++) {
                    if (i === 1 && !row[i]) {
                        break;
                    }
                    if (i < keys.length) {
                        cellObj[keys[i]] = row[i] || '';

                    }
                }
                if (cellObj.gmtOrderReceived) {
                    var date = new Date(1900, 0, cellObj.gmtOrderReceived-1).toLocaleString();
                    cellObj.gmtOrderReceived=date;

                    if(cellObj.gmtDispatch){
                        var date = new Date(1900, 0, cellObj.gmtDispatch-1).toLocaleString();
                        cellObj.gmtDispatch=date;
                    }

                    if(cellObj.gmtOutboundCust){
                        var date = new Date(1900, 0, cellObj.gmtOutboundCust-1).toLocaleString();
                        cellObj.gmtOutboundCust=date;
                    }

                    if(cellObj.gmtInboundPickup){
                        var date = new Date(1900, 0, cellObj.gmtInboundPickup-1).toLocaleString();
                        cellObj.gmtInboundPickup=date;
                    }

                    if(cellObj.gmtSap){
                        var date = new Date(1900, 0, cellObj.gmtSap-1).toLocaleString();
                        cellObj.gmtSap=date;
                    }

                    if(cellObj.gmtPod){
                        var date = new Date(1900, 0, cellObj.gmtPod-1).toLocaleString();
                        cellObj.gmtPod=date;
                    }

                    if(cellObj.gmtPhase1Dispatch){
                        var date = new Date(1900, 0, cellObj.gmtPhase1Dispatch-1).toLocaleString();
                        cellObj.gmtPhase1Dispatch=date;
                    }

                    if(cellObj.gmtPhase1Depart){
                        var date = new Date(1900, 0, cellObj.gmtPhase1Depart-1).toLocaleString();
                        cellObj.gmtPhase1Depart=date;
                    }

                    if(cellObj.gmtPhase1Arrival == '铁运'){
                        cellObj.gmtPhase1Arrival="";
                    }

                    if(cellObj.gmtPhase1Arrival){
                        var date = new Date(1900, 0, cellObj.gmtPhase1Arrival-1).toLocaleString();
                        cellObj.gmtPhase1Arrival=date;
                    }

                    if(cellObj.gmtPhase2Inbound){
                        var date = new Date(1900, 0, cellObj.gmtPhase2Inbound-1).toLocaleString();
                        cellObj.gmtPhase2Inbound=date;
                    }

                    if(cellObj.gmtPhase2Depart){
                        var date = new Date(1900, 0, cellObj.gmtPhase2Depart-1).toLocaleString();
                        cellObj.gmtPhase2Depart=date;
                    }

                    if(cellObj.gmtPhase2Arrival){
                        var date = new Date(1900, 0, cellObj.gmtPhase2Arrival-1).toLocaleString();
                        cellObj.gmtPhase2Arrival=date;
                    }

                    if(cellObj.gmtPhase3Inbound){
                        var date = new Date(1900, 0, cellObj.gmtPhase3Inbound-1).toLocaleString();
                        cellObj.gmtPhase3Inbound=date;
                    }

                    if(cellObj.gmtPhase3Depart){
                        var date = new Date(1900, 0, cellObj.gmtPhase3Depart-1).toLocaleString();
                        cellObj.gmtPhase3Depart=date;
                    }

                    if(cellObj.gmtPhase3Arrival){
                        var date = new Date(1900, 0, cellObj.gmtPhase3Arrival-1).toLocaleString();
                        cellObj.gmtPhase3Arrival=date;
                    }

                    if(cellObj.gmtStandardDelivery){
                        var date = new Date(1900, 0, cellObj.gmtStandardDelivery-1).toLocaleString();
                        cellObj.gmtStandardDelivery=date;
                    }

                    if(cellObj.gmtActualDelivery){
                        var date = new Date(1900, 0, cellObj.gmtActualDelivery-1).toLocaleString();
                        cellObj.gmtActualDelivery=date;
                    }

                    if(cellObj.gmtArrival){
                        var date = new Date(1900, 0, cellObj.gmtArrival-1).toLocaleString();
                        cellObj.gmtArrival=date;
                    }
                    requestList.push(cellObj);
                }
            }
            _.map(requestList, function () {
                // item.isUrgent = item.isUrgent == baseConfig.available.enable ? true : false;
                // item.isSencondhand = item.isSencondhand == baseConfig.available.enable ? false : true;
                // item.isMobile = item.isMobile == baseConfig.available.enable ? true : false;
                // item.isPick = item.isPick == baseConfig.available.enable ? true : false;
                // item.isDeliv = item.isDeliv == baseConfig.available.enable ? true : false;
                // if (item.deliveryTime == baseConfig.deliveryTime.am) {
                //     item.deliveryTime = 0;
                // } else if (item.deliveryTime == baseConfig.deliveryTime.pm) {
                //     item.deliveryTime = 1;
                // }
            });
        }
    }
    if (!isXls) {
        if (callback) callback(null);
    } else {
        if (callback) callback(requestList);
    }
};


/**
 * 传递客户订单数据到服务器(客户)
 * @param list 列表
 */
function uploadCustomOTD2Service(list, callback) {
    var sheet = null;

    var keys = [
        'customerOrderCode','orderCode','vehicleVin','vehicleCode','vehicleName','agentName',
        'receiptProvince','receiptCity','miles','pickTime','shipmentTime','onWayLocation','arriveTime',
        'orderStatus','transportType','remark','remarkDesc','inBoundUnlcn','outBoundUnlcn','customerName'
    ];

    var requestList = [];
    var isXls = false;
    if (list && list.length > 0) {
        isXls = true;
        sheet = list[0];
        if (sheet.data.length > 1) {
            for (var j = 1; j < sheet.data.length; j++) {
                var row = sheet.data[j];
                var cellObj = {};
                for (var i = 0; i < row.length; i++) {
                    if (i === 1 && !row[i]) {
                        break;
                    }
                    if (i < keys.length) {
                        cellObj[keys[i]] = row[i] || '';

                    }
                }
                if (cellObj.customerOrderCode) {

                    if(cellObj.pickTime){
                        var date = new Date(1900, 0, cellObj.pickTime-1).toLocaleString();
                        cellObj.pickTime=date;
                    }

                    if(cellObj.shipmentTime){
                        var date = new Date(1900, 0, cellObj.shipmentTime-1).toLocaleString();
                        cellObj.shipmentTime=date;
                    }

                    if(cellObj.arriveTime){
                        var date = new Date(1900, 0, cellObj.arriveTime-1).toLocaleString();
                        cellObj.arriveTime=date;
                    }

                    if(cellObj.inBoundUnlcn){
                        var date = new Date(1900, 0, cellObj.inBoundUnlcn-1).toLocaleString();
                        cellObj.arriveTime=date;
                    }

                    if(cellObj.outBoundUnlcn){
                        var date = new Date(1900, 0, cellObj.outBoundUnlcn-1).toLocaleString();
                        cellObj.arriveTime=date;
                    }

                    requestList.push(cellObj);
                }
            }
            _.map(requestList, function () {
                // item.isUrgent = item.isUrgent == baseConfig.available.enable ? true : false;
                // item.isSencondhand = item.isSencondhand == baseConfig.available.enable ? false : true;
                // item.isMobile = item.isMobile == baseConfig.available.enable ? true : false;
                // item.isPick = item.isPick == baseConfig.available.enable ? true : false;
                // item.isDeliv = item.isDeliv == baseConfig.available.enable ? true : false;
                // if (item.deliveryTime == baseConfig.deliveryTime.am) {
                //     item.deliveryTime = 0;
                // } else if (item.deliveryTime == baseConfig.deliveryTime.pm) {
                //     item.deliveryTime = 1;
                // }
            });
        }
    }
    if (!isXls) {
        if (callback) callback(null);
    } else {
        if (callback) callback(requestList);
    }
};

/**
 * 上传文件
 * @param req
 * @param res
 * @param callback
 */
uploadService.uploadExcel = function (req, res, callback) {
    // parse a file uploadService
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.keepExtensions = true;
    form.parse(req, function(err, fields, files) {
        if (files) {
            var efile = files.file;
            //var fileName = efile.name;
            var path = efile.path;
            var list = null;
            try{
                list = xlsx.parse(path);
            } catch (e) {
                list = [];
            }
            fs.unlinkSync(path);
            uploadExcel2Service(list, callback);
        }
    });
};

/**
 * 上传文件
 * @param req
 * @param res
 * @param callback
 */
uploadService.uploadExcel1 = function (req, res, callback) {
    // parse a file uploadService
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.keepExtensions = true;
    form.parse(req, function(err, fields, files) {
        if (files) {
            var efile = files.file;
            //var fileName = efile.name;
            var path = efile.path;
            var list = null;
            try{
                list = xlsx.parse(path);
            } catch (e) {
                list = [];
            }
            fs.unlinkSync(path);
            uploadExcel1Service(list, callback);
        }
    });
};

/**
 * 上传文件
 * @param req
 * @param res
 * @param callback
 */
uploadService.uploadOTDExcel = function (req, res, callback) {
    // parse a file uploadService
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.keepExtensions = true;

    form.parse(req, function(err, fields, files) {
        if (files) {
            var efile = files.file;
            //var fileName = efile.name;
            var path = efile.path;
            // fd.append('logo', efile);
            var list = null;
            try{
                list = xlsx.parse(path);
            } catch (e) {
                list = [];
            }
            fs.unlinkSync(path);
            uploadOTDExcel2Service(list, callback);
        }
    });
};


/**
 * 上传客户订单文件
 * @param req
 * @param res
 * @param callback
 */
uploadService.uploadCutomOTDExcel = function (req, res, callback) {
    // parse a file uploadService
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.keepExtensions = true;

    form.parse(req, function(err, fields, files) {
        if (files) {
            var efile = files.file;
            //var fileName = efile.name;
            var path = efile.path;
            // fd.append('logo', efile);
            var list = null;
            try{
                list = xlsx.parse(path);
            } catch (e) {
                list = [];
            }
            fs.unlinkSync(path);
            uploadCustomOTD2Service(list, callback);
        }
    });
};


uploadService.implExcel = function (req, list, callback) {
    req.body.excelData = JSON.stringify(list);
    post('/labor_price_import/import', req, callback);
};

uploadService.vehicleExcel = function (req, list, callback) {
    req.body.excelData = JSON.stringify(list);
    post('/vehicle_fuel_import/import', req, callback);
};

uploadService.orderOTDExcel = function (req, list, callback){
    req.body.excelData = JSON.stringify(list);
    postkas('/otd/saveExcel', req, callback);
};

uploadService.orderCustomOTDExcel = function (req, list, callback){
    req.body.excelData = JSON.stringify(list);
    postotd('/otd/saveCustomerExcel', req, callback);
};


